#!/usr/bin/env bash
# Copyright (c) 2021 Presto Labs Pte. Ltd.
# Author:  eddys

set -eu -o pipefail -o noglob

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "${SCRIPT_DIR}"

set +u
# activate base env, assuming hashdeep installed here
source $HOME/miniconda3/bin/activate
set -u

# print jenkins parameters
echo "SRC_PATH: ${SRC_PATH}"
echo "DST_PATH: ${DST_PATH}"
echo "MACHINE: ${MACHINE}"
echo "START_DATE: ${START_DATE}"
echo "END_DATE: ${END_DATE}"

LOG_DIR=$WORKSPACE/logs/$BUILD_NUMBER/
devider='=================================================='

[ ! -d "${LOG_DIR}" ] && mkdir -p "${LOG_DIR}"


while (( $(date +%s -d ${START_DATE}) <= $(date +%s -d ${END_DATE}) )); do
  TARGET_DATE=$(date -d ${START_DATE} +%Y%m%d)
  
  # exit if source directory is a symlink
  if [[ -L "${SRC_PATH}/${MACHINE}/${TARGET_DATE}" && -d "${SRC_PATH}/${MACHINE}/${TARGET_DATE}" ]]; then
    exit 1
  fi

  # check if the directory is empty
  if test -n "$(find ${SRC_PATH}/${MACHINE}/${TARGET_DATE} -maxdepth 1 -empty)"; then
    echo "No files found on ${SRC_PATH}/${MACHINE}/${TARGET_DATE}."

    # increment START_DATE
    START_DATE=$(date -d "${START_DATE} + 1 day" "+%Y%m%d")

    continue
  else
    # rsync to archive nfs
    rsync -av --bwlimit=100000 "${SRC_PATH}/${MACHINE}/${TARGET_DATE}" "${DST_PATH}/${MACHINE}/"

    # generate the audit file from the source directory
    # audit using hashdeep https://github.com/jessek/hashdeep
    # conda install -c conda-forge -y hashdeep
    cd ${SRC_PATH}
    hashdeep -rl ${MACHINE}/${TARGET_DATE} > $LOG_DIR/${MACHINE}_${TARGET_DATE}_hash.log

    # run the audit on the archive nfs
    cd ${DST_PATH}
    printf "%50.50s\n" "$devider"
    echo "Audit ${MACHINE}/${TARGET_DATE} start"
    hashdeep -ravvl -k ${LOG_DIR}/${MACHINE}_${TARGET_DATE}_hash.log ${MACHINE}/${TARGET_DATE}
    echo "Audit $MACHINE/${TARGET_DATE} end"
    printf "%50.50s\n" "$devider"

    # delete source directory upon succesful audit
    echo "Deleting source..."
    rm -r "${SRC_PATH}/${MACHINE}/${TARGET_DATE}"

    # create symmlink
    echo "Creating symlink..."
    ln -s "${DST_PATH}/${MACHINE}/${TARGET_DATE}" "${SRC_PATH}/${MACHINE}/"

    # increment START_DATE
    START_DATE=$(date -d "${START_DATE} + 1 day" "+%Y%m%d")

  fi

done

source $HOME/miniconda3/bin/deactivate
